/* global window */
import axios from 'axios'
import cloneDeep from 'lodash.clonedeep'
import pathToRegexp from 'path-to-regexp'
import uuidV4 from 'uuid/v4'
import { message } from 'antd'
import { prefix, head, isCiphertext } from 'config'
import { encryptAesAndRsa, decryptAesAndRsa } from './secret'

let requestInterceptor,responseInterceptor
if(isCiphertext){
  //请求拦截器
  requestInterceptor = axios.interceptors.request.use(config =>{
    if(config.method === "post"){
      //混淆加密
      config.data = {'encryptStr': encryptAesAndRsa(config.data)}
    }
    // console.log(config)
    return config
  },function (error){
    return Promise.reject(error)
  })

  //响应拦截器
  responseInterceptor = axios.interceptors.response.use(res =>{
    //混淆解密
    if(typeof(res.data) === "string"){
      res.data = JSON.parse(decryptAesAndRsa(res.data))
    }
    // console.log(res)
    return res
  },function (error){
    return Promise.reject(error)
  })
} else {
  //取消拦截器
  if(!requestInterceptor){
    axios.interceptors.request.eject(requestInterceptor)
  }
  if(!responseInterceptor){
    axios.interceptors.request.eject(responseInterceptor)
  }
}

const fetch = (options) => {
  let {
    method = 'post',
    headmethod,
    url,
    data,
  } = options

  // 请求头 language
  let language = `zh_CN`
  if(!!window.localStorage.getItem(`${prefix}language`)) language = window.localStorage.getItem(`${prefix}language`)
  // 请求头 timestamp
  const timestamp = new Date().getTime()
  // 请求头 sys_track_code
  const sys_track_code = uuidV4()
  const headers = { ...head, method: headmethod, language, timestamp, sys_track_code }

  const cloneData = cloneDeep(data)

  try {
    let domain = ''
    if (url.match(/[a-zA-z]+:\/\/[^/]*/)) {
      [domain] = url.match(/[a-zA-z]+:\/\/[^/]*/)
      url = url.slice(domain.length)
    }
    const match = pathToRegexp.parse(url)
    url = pathToRegexp.compile(url)(data)
    for (let item of match) {
      if (item instanceof Object && item.name in cloneData) {
        delete cloneData[item.name]
      }
    }
    url = domain + url
  } catch (e) {
    message.error(e.message)
  }

  switch (method.toLowerCase()) {
    case 'get':
      return axios.get(url, {
        params: {
          head: headers,
          body: cloneData,
        },
      })
    case 'delete':
      return axios.delete(url, {
        data: {
          head: headers,
          body: cloneData,
        },
      })
    case 'post':
      return axios.post(url, {
        head: headers,
        body: cloneData,
      })
    case 'put':
      return axios.put(url, {
        head: headers,
        body: cloneData,
      })
    case 'patch':
      return axios.patch(url, {
        head: headers,
        body: cloneData,
      })
    default:
      return axios(options)
  }
}

export default function request (options) {

  return fetch(options).then((response) => {
    const { statusText, status } = response
    let data = options.fetchType === 'YQL' ? response.data.query.results.json : response.data
    if (data instanceof Array) {
      data = {
        list: data,
      }
    }
    return Promise.resolve({
      success: true,
      message: statusText,
      statusCode: status,
      ...data,
    })
  }).catch((error) => {
    const { response } = error
    let msg
    let statusCode
    if (response && response instanceof Object) {
      const { data, statusText } = response
      statusCode = response.status
      msg = data.message || statusText
    } else {
      statusCode = 600
      msg = error.message || 'Network Error'
    }

    /* eslint-disable */
    return Promise.reject({ success: false, statusCode, message: msg })
  })
}
